'use strict';

const Service = require('egg').Service;

class SocialService extends Service {
  // 分享搭配
  async shareOutfit(userId, shareData) {
    const { outfitId, platform, caption, isPublic } = shareData;

    // 验证搭配是否存在且属于用户
    const outfit = await this.ctx.model.Outfit.findOne({
      where: { id: outfitId, user_id: userId }
    });

    if (!outfit) {
      throw new Error('搭配不存在或无权限');
    }

    // 创建分享记录
    const share = await this.ctx.model.Share.create({
      user_id: userId,
      target_type: 'outfit',
      target_id: outfitId,
      platform,
      caption,
      is_public: isPublic
    });

    // 更新搭配的分享状态
    await outfit.update({
      is_public: isPublic,
      shared_at: new Date()
    });

    return share;
  }

  // 获取公开搭配
  async getPublicOutfits(options = {}) {
    const { page = 1, pageSize = 20, style, season, sortBy = 'latest' } = options;
    const { Op } = this.app.Sequelize;

    const where = { is_public: true };
    
    if (style) {
      where.style = style;
    }
    
    if (season) {
      where.season = season;
    }

    // 排序规则
    let order = [['created_at', 'DESC']];
    if (sortBy === 'popular') {
      order = [['like_count', 'DESC'], ['created_at', 'DESC']];
    } else if (sortBy === 'rating') {
      order = [['rating', 'DESC'], ['created_at', 'DESC']];
    }

    const result = await this.ctx.model.Outfit.findAndCountAll({
      where,
      include: [
        {
          model: this.ctx.model.User,
          as: 'user',
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: this.ctx.model.Clothing,
          as: 'clothes',
          through: {
            attributes: [],
            paranoid: false  // 中间表不使用软删除
          },
          attributes: ['id', 'name', 'main_image', 'color']
        }
        // 暂时移除Share关联，避免数据库字段问题
        // {
        //   model: this.ctx.model.Share,
        //   as: 'shares',
        //   where: { is_public: true },
        //   required: false
        // }
      ],
      order,
      limit: pageSize,
      offset: (page - 1) * pageSize
    });

    return {
      list: result.rows,
      total: result.count,
      page,
      pageSize
    };
  }

  // 点赞搭配
  async likeOutfit(userId, outfitId) {
    // 检查是否已经点赞
    const existingLike = await this.ctx.model.Like.findOne({
      where: {
        user_id: userId,
        target_type: 'outfit',
        target_id: outfitId
      }
    });

    if (existingLike) {
      // 取消点赞
      await existingLike.destroy();
      
      // 更新搭配点赞数
      await this.ctx.model.Outfit.decrement('like_count', {
        where: { id: outfitId }
      });

      return { liked: false, action: 'unliked' };
    } else {
      // 添加点赞
      await this.ctx.model.Like.create({
        user_id: userId,
        target_type: 'outfit',
        target_id: outfitId
      });

      // 更新搭配点赞数
      await this.ctx.model.Outfit.increment('like_count', {
        where: { id: outfitId }
      });

      return { liked: true, action: 'liked' };
    }
  }

  // 评论搭配
  async commentOutfit(userId, outfitId, commentData) {
    const { content, rating } = commentData;

    // 验证搭配是否存在
    const outfit = await this.ctx.model.Outfit.findByPk(outfitId);
    if (!outfit) {
      throw new Error('搭配不存在');
    }

    // 创建评论
    const comment = await this.ctx.model.Comment.create({
      user_id: userId,
      target_type: 'outfit',
      target_id: outfitId,
      content,
      rating
    });

    // 更新搭配评论数
    await this.ctx.model.Outfit.increment('comment_count', {
      where: { id: outfitId }
    });

    // 如果有评分，更新搭配平均评分
    if (rating) {
      await this.updateOutfitRating(outfitId);
    }

    // 获取完整的评论信息
    const fullComment = await this.ctx.model.Comment.findByPk(comment.id, {
      include: [{
        model: this.ctx.model.User,
        as: 'user',
        attributes: ['id', 'username', 'avatar']
      }]
    });

    return fullComment;
  }

  // 获取搭配评论
  async getOutfitComments(outfitId, options = {}) {
    const { page = 1, pageSize = 20 } = options;

    const result = await this.ctx.model.Comment.findAndCountAll({
      where: {
        target_type: 'outfit',
        target_id: outfitId,
        is_deleted: 0
      },
      include: [
        {
          model: this.ctx.model.User,
          as: 'user',
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: this.ctx.model.Comment,
          as: 'replies',
          include: [{
            model: this.ctx.model.User,
            as: 'user',
            attributes: ['id', 'username', 'avatar']
          }]
        }
      ],
      order: [['created_at', 'DESC']],
      limit: pageSize,
      offset: (page - 1) * pageSize
    });

    return {
      list: result.rows,
      total: result.count,
      page,
      pageSize
    };
  }

  // 关注用户
  async followUser(followerId, followingId) {
    // 检查是否已经关注
    const existingFollow = await this.ctx.model.Follow.findOne({
      where: {
        follower_id: followerId,
        following_id: followingId
      }
    });

    if (existingFollow) {
      if (existingFollow.is_active) {
        // 取消关注
        await existingFollow.update({ is_active: false });
        return { followed: false, action: 'unfollowed' };
      } else {
        // 重新关注
        await existingFollow.update({ is_active: true });
        return { followed: true, action: 'followed' };
      }
    } else {
      // 新建关注关系
      await this.ctx.model.Follow.create({
        follower_id: followerId,
        following_id: followingId,
        is_active: true
      });
      return { followed: true, action: 'followed' };
    }
  }

  // 获取关注列表
  async getFollowing(userId, options = {}) {
    const { page = 1, pageSize = 20 } = options;

    const result = await this.ctx.model.Follow.findAndCountAll({
      where: {
        follower_id: userId,
        is_active: true
      },
      include: [{
        model: this.ctx.model.User,
        as: 'following',
        attributes: ['id', 'username', 'avatar', 'bio']
      }],
      order: [['created_at', 'DESC']],
      limit: pageSize,
      offset: (page - 1) * pageSize
    });

    return {
      list: result.rows.map(follow => follow.following),
      total: result.count,
      page,
      pageSize
    };
  }

  // 获取粉丝列表
  async getFollowers(userId, options = {}) {
    const { page = 1, pageSize = 20 } = options;

    const result = await this.ctx.model.Follow.findAndCountAll({
      where: {
        following_id: userId,
        is_active: true
      },
      include: [{
        model: this.ctx.model.User,
        as: 'follower',
        attributes: ['id', 'username', 'avatar', 'bio']
      }],
      order: [['created_at', 'DESC']],
      limit: pageSize,
      offset: (page - 1) * pageSize
    });

    return {
      list: result.rows.map(follow => follow.follower),
      total: result.count,
      page,
      pageSize
    };
  }

  // 获取好友推荐
  async getFriendRecommendations(userId) {
    // 获取用户的关注列表
    const following = await this.ctx.model.Follow.findAll({
      where: { follower_id: userId, is_active: true },
      attributes: ['following_id']
    });

    const followingIds = following.map(f => f.following_id);
    followingIds.push(userId); // 排除自己

    // 基于共同关注推荐
    const recommendations = await this.ctx.model.User.findAll({
      where: {
        id: { [this.app.Sequelize.Op.notIn]: followingIds }
      },
      attributes: ['id', 'username', 'avatar', 'bio'],
      limit: 10,
      order: [['created_at', 'DESC']]
    });

    return recommendations;
  }

  // 获取动态流
  async getFeed(userId, options = {}) {
    const { page = 1, pageSize = 20 } = options;

    // 获取关注的用户ID
    const following = await this.ctx.model.Follow.findAll({
      where: { follower_id: userId, is_active: true },
      attributes: ['following_id']
    });

    const followingIds = following.map(f => f.following_id);
    followingIds.push(userId); // 包含自己的动态

    // 获取动态（分享的搭配）
    const result = await this.ctx.model.Share.findAndCountAll({
      where: {
        user_id: { [this.app.Sequelize.Op.in]: followingIds },
        is_public: true,
        target_type: 'outfit'  // 只获取搭配分享
      },
      include: [
        {
          model: this.ctx.model.User,
          as: 'user',
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: this.ctx.model.Outfit,
          as: 'outfit',
          include: [{
            model: this.ctx.model.Clothing,
            as: 'clothes',
            through: {
              attributes: [],
              paranoid: false  // 中间表不使用软删除
            },
            attributes: ['id', 'name', 'main_image']
          }]
        }
      ],
      order: [['created_at', 'DESC']],
      limit: pageSize,
      offset: (page - 1) * pageSize
    });

    return {
      list: result.rows,
      total: result.count,
      page,
      pageSize
    };
  }

  // 举报内容
  async reportContent(userId, reportData) {
    const { contentType, contentId, reason, description } = reportData;

    // 这里可以创建举报记录表，暂时简化处理
    // 实际应用中需要管理员审核系统

    console.log('Content reported:', {
      reporter: userId,
      contentType,
      contentId,
      reason,
      description,
      timestamp: new Date()
    });

    return { success: true, message: '举报已提交，我们会尽快处理' };
  }

  // 更新搭配平均评分
  async updateOutfitRating(outfitId) {
    const comments = await this.ctx.model.Comment.findAll({
      where: {
        target_type: 'outfit',
        target_id: outfitId,
        rating: { [this.app.Sequelize.Op.ne]: null }
      },
      attributes: ['rating']
    });

    if (comments.length > 0) {
      const totalRating = comments.reduce((sum, comment) => sum + comment.rating, 0);
      const averageRating = (totalRating / comments.length).toFixed(1);

      await this.ctx.model.Outfit.update(
        { rating: averageRating },
        { where: { id: outfitId } }
      );
    }
  }
}

module.exports = SocialService;
